﻿/*
=======================================================
    Bill【单据】
=======================================================
*/

namespace Services
{
    public interface IBillLogic : ILogic<BillModel, BillFilterModel>
    {
        bool BackForIn(BillModel model);
        bool BackForOut(BillModel model);
        bool ConfirmForIn(BillModel model);
        bool ConfirmForOut(BillModel model);
        bool SubmitForIn(BillModel model);
        bool SubmitForOut(BillModel model);
    }


    public class BillLogic : BaseLogic<BillModel, BillFilterModel, Bill, IBillRepository, IBillMapping, IBillService>, IBillLogic
    {
        #region Ioc
        private readonly IStockRepository _stockRepository;
        private readonly IStockMapping _stockMapping;

        private readonly IBillDetailRepository _billDetailRepository;
        private readonly IBillDetailMapping _billDetailMapping;

        private readonly ICreateCode _ICreateCode;

        private readonly IGroupInfoRepository _IGroupInfoRepository;
        public BillLogic(ICurrentUser currentUser, IBillRepository repository, IBillMapping mapping, IBillService service, IStockMapping __stockMapping, IStockRepository __stockRepository, IBillDetailRepository __billDetailRepository, IBillDetailMapping __billDetailMapping, ICreateCode iCreateCode, IGroupInfoRepository __IGroupInfoRepository)
            : base(currentUser, repository, mapping, service)
        {
            _stockMapping = __stockMapping;
            _stockRepository = __stockRepository;

            _billDetailRepository = __billDetailRepository;
            _billDetailMapping = __billDetailMapping;
            _ICreateCode = iCreateCode;
            _IGroupInfoRepository = __IGroupInfoRepository;
        }
        #endregion

        #region Insert
        public override BillModel Insert(BillModel model)
        {
            //补全需要赋值的数据
            model.CreateUserID = _currentUser.CurrentUserInfo.UserID;
            model.CreateUserName = _currentUser.CurrentUserInfo.UserName;
            model.GroupInfoID = _currentUser.CurrentUserInfo.LoginTypeID;
            model.CreateDate = DateTime.Now;
            model.Status = (int)Bill_Status.创建中;

            //判断入库单号是否填写，如果没有填写，自动生成，如果填写，判断是否有重复数据
            if (!model.Code.IsEmpty())
            {
                var where = Expressionable.Create<Bill>();
                where = where.And(x => x.Code == model.Code);
                var count = _repository.GetCount(where);
                if (count > 0)
                {
                    throw new CustomException("入库单号重复！");
                }
            }
            else
            {
                model.Code = _ICreateCode.GetBillCode(Gx.GetEnumByValue<Bill_InOutType>(model.InOutType));
            }


            // 处理详情
            if (model.InOutType == (int)Bill_InOutType.入库)
            {
                var codeTemp = _ICreateCode.GetStockWireropeCode(model.GroupInfoID);

                string code = DateTime.Now.ToString("yyMM");

                var where3 = Expressionable.Create<GroupInfo>();
                where3 = where3.And(x => x.GroupInfoID == model.GroupInfoID);

                var info = _IGroupInfoRepository.GetModel(where3);

                code = string.Format("{0}-{1}", info.Code, code);

                foreach (var item in model.BillDetailModels)
                {
                    if (!item.Code.IsEmpty())
                    {
                        var where = Expressionable.Create<Stock>();
                        where = where.And(x => x.Code == item.Code);
                        var count = _stockRepository.GetCount(where);
                        if (count > 0)
                        {
                            throw new CustomException("绳子编码: " + item.Code + "重复！");
                        }

                        var count1 = model.BillDetailModels.Where(x => x.Code == item.Code).Count();
                        if (count1 > 1)
                        {
                            throw new CustomException("绳子编码: " + item.Code + "重复！");
                        }
                    }
                    else
                    {
                        item.Code = code + (++codeTemp).ToString().PadLeft(4, '0');
                    }
                }
            }

            model.BillID = _repository.InsertForAdmin(_mapping.Model2Entity(model), _billDetailMapping.Model2Entity(model.BillDetailModels));

            return model;
        }
        #endregion

        #region Update
        public override int Update(BillModel model)
        {
            //判断入库单号是否填写，如果没有填写，自动生成，如果填写，判断是否有重复数据
            if (!model.Code.IsEmpty())
            {
                var where = Expressionable.Create<Bill>();
                where = where.And(x => x.Code == model.Code);
                where = where.And(x => x.BillID != model.BillID);
                var count = _repository.GetCount(where);
                if (count > 0)
                {
                    throw new CustomException("入库单号重复！");
                }
            }
            else
            {
                model.Code = _ICreateCode.GetBillCode(Gx.GetEnumByValue<Bill_InOutType>(model.InOutType));
            }


            if (model.InOutType == (int)Bill_InOutType.入库)
            {
                // 处理详情
                var codeTemp = _ICreateCode.GetStockWireropeCode(model.GroupInfoID);

                string code = DateTime.Now.ToString("yyMM");

                var where3 = Expressionable.Create<GroupInfo>();
                where3 = where3.And(x => x.GroupInfoID == model.GroupInfoID);

                var info = _IGroupInfoRepository.GetModel(where3);

                code = string.Format("{0}-{1}", info.Code, code);
                foreach (var item in model.BillDetailModels)
                {
                    if (!item.Code.IsEmpty())
                    {
                        var where = Expressionable.Create<Stock>();
                        where = where.And(x => x.Code == item.Code);
                        var count = _stockRepository.GetCount(where);
                        if (count > 0)
                        {
                            throw new CustomException("绳子编码: " + item.Code + "重复！");
                        }

                        var count1 = model.BillDetailModels.Where(x => x.Code == item.Code).Count();
                        if (count1 > 1)
                        {
                            throw new CustomException("绳子编码: " + item.Code + "重复！");
                        }
                    }
                    else
                    {
                        item.Code = code + (++codeTemp).ToString().PadLeft(4, '0');
                    }
                }
            }

            _repository.UpdateForAdmin(_mapping.Model2Entity(model), _billDetailMapping.Model2Entity(model.BillDetailModels));

            return 1;
        }
        #endregion

        #region Delete
        public override int Delete(int id)
        {
            _repository.DeleteForAdmin(id);

            return 1;
        }
        #endregion

        #region GetByID
        public override BillModel GetByID(int id)
        {
            var info = GetModel(new BillFilterModel { _BillID = id });

            if (info != null)
            {
                var where = Expressionable.Create<BillDetail>();
                where = where.And(x => x.BillID == id);
                var detailList = _billDetailRepository.GetSearch(where).ToList();

                info.BillDetailModels = _billDetailMapping.Entity2Model(detailList);
            }

            return info;
        }
        #endregion

        #region 入库提交  SubmitForIn
        public bool SubmitForIn(BillModel model)
        {
            int id;
            if (model.BillID == 0)
            {
                id = Insert(model).BillID;
            }
            else
            {
                Update(model);
                id = model.BillID;
            }

            var info = GetByID(id);

            if (info == null)
            {
                throw new CustomException("当前单子不存在: " + id);
            }

            if (info.Status != (int)Bill_Status.创建中)
            {
                throw new CustomException("当前单子状态不存在: " + id);
            }

            info.SubmitUserID = _currentUser.CurrentUserInfo.UserID;
            info.SubmitUserName = _currentUser.CurrentUserInfo.UserName;
            info.SubmitDate = DateTime.Now;
            info.Status = (int)Bill_Status.验收中;
            info.BackReason = null;

            _repository.Update(_mapping.Model2Entity(info));

            return true;
        }
        #endregion

        #region 出库提交  SubmitForOut
        public bool SubmitForOut(BillModel model)
        {
            int id;
            if (model.BillID == 0)
            {
                id = Insert(model).BillID;
            }
            else
            {
                Update(model);
                id = model.BillID;
            }

            var info = GetByID(id);

            if (info == null)
            {
                throw new CustomException("当前单子不存在: " + id);
            }

            if (info.Status != (int)Bill_Status.创建中)
            {
                throw new CustomException("当前单子状态不存在: " + id);
            }

            info.SubmitUserID = _currentUser.CurrentUserInfo.UserID;
            info.SubmitUserName = _currentUser.CurrentUserInfo.UserName;
            info.SubmitDate = DateTime.Now;
            info.Status = (int)Bill_Status.确认中;
            info.BackReason = null;

            _repository.Update(_mapping.Model2Entity(info));

            return true;
        }
        #endregion

        #region 入库退回  BackForIn
        public bool BackForIn(BillModel model)
        {
            var info = GetByID(model.BillID);

            if (info == null)
            {
                throw new CustomException("当前单子不存在: " + model.BillID);
            }

            if (info.Status != (int)Bill_Status.验收中)
            {
                throw new CustomException("当前单子状态不存在: " + model.BillID);
            }

            if (model.BackReason.IsEmpty())
            {
                throw new CustomException("退回原因为空: " + model.BillID);
            }

            model.BackUserID = _currentUser.CurrentUserInfo.UserID;
            model.BackUserName = _currentUser.CurrentUserInfo.UserName;
            model.BackDate = DateTime.Now;
            model.Status = (int)Bill_Status.创建中;

            _repository.Update(_mapping.Model2Entity(model));

            return true;
        }
        #endregion

        #region 出库退回  BackForOut
        public bool BackForOut(BillModel model)
        {
            var info = GetByID(model.BillID);

            if (info == null)
            {
                throw new CustomException("当前单子不存在: " + model.BillID);
            }

            if (info.Status != (int)Bill_Status.确认中)
            {
                throw new CustomException("当前单子状态不存在: " + model.BillID);
            }

            if (model.BackReason.IsEmpty())
            {
                throw new CustomException("退回原因为空: " + model.BillID);
            }

            model.BackUserID = _currentUser.CurrentUserInfo.UserID;
            model.BackUserName = _currentUser.CurrentUserInfo.UserName;
            model.BackDate = DateTime.Now;
            model.Status = (int)Bill_Status.创建中;
            _repository.Update(_mapping.Model2Entity(model));

            return true;
        }
        #endregion

        #region 入库确认  ConfirmForIn
        public bool ConfirmForIn(BillModel model)
        {
            var info = GetByID(model.BillID);

            if (info == null)
            {
                throw new CustomException("当前单子不存在: " + model.BillID);
            }

            if (info.Status != (int)Bill_Status.验收中)
            {
                throw new CustomException("当前单子状态不存在: " + model.BillID);
            }

            //判断detail中的绳子编码是否唯一
            //var where = Expressionable.Create<BillDetail>();
            //where = where.And(x => x.BillID == model.BillID);
            var detailList = model.BillDetailModels;
            var hasRepeat = false;
            var codeStr = string.Empty;
            foreach (var item in detailList)
            {
                var where1 = Expressionable.Create<Stock>();
                where1 = where1.And(x => x.Code == item.Code);
                var count = _stockRepository.GetCount(where1);
                if (count > 0)
                {
                    codeStr = item.Code;
                    hasRepeat = true;
                    break;
                }

                var count1 = detailList.Where(x => x.Code == item.Code).Count();
                if (count1 > 1)
                {
                    codeStr = item.Code;
                    hasRepeat = true;
                    break;
                }
            }

            if (hasRepeat)
            {
                throw new CustomException("绳子编码: " + codeStr + "重复！");
            }

            model.ConfirmUserID = _currentUser.CurrentUserInfo.UserID;
            model.ConfirmUserName = _currentUser.CurrentUserInfo.UserName;
            model.ConfirmDate = DateTime.Now;
            model.Status = (int)Bill_Status.已验收;

            //Update(info);

            //通过detail数据创建stock数据
            List<Stock> list = new List<Stock>();
            foreach (var item in detailList)
            {
                Stock stock = new Stock();
                stock.GroupInfoID = item.GroupInfoID; ;
                stock.BillID = item.BillID;
                stock.BillDetailID = item.BillDetailID;
                stock.WarehouseID = item.WarehouseID;
                stock.WarehouseName = item.WarehouseName;
                stock.WarehousePositionID = item.WarehousePositionID.Value;
                stock.WarehousePositionName = item.WarehousePositionName;
                stock.Code = item.Code;
                stock.GuiGe = item.GuiGe;
                stock.Diameter = item.Diameter;
                stock.Cnt = item.Cnt;
                stock.Name = item.Name;
                stock.NianJu = item.NianJu;
                stock.MpaID = item.MpaID;
                stock.MpaName = item.MpaName;
                stock.SurfaceStatusID = item.SurfaceStatusID;
                stock.SurfaceStatusName = item.SurfaceStatusName;
                stock.TwistingTypeID = item.TwistingTypeID;
                stock.TwistingTypeName = item.TwistingTypeName;
                stock.LengthNum = item.LengthNum;
                stock.KeepDay = item.KeepDay;
                stock.SupplierID = item.SupplierID;
                stock.SupplierName = item.SupplierName;
                stock.ProducerID = item.ProducerID;
                stock.ProducerName = item.ProducerName;
                stock.ChuChang_Files = item.ChuChang_FilesList.GetFileString();
                stock.YanShou_Files = item.YanShou_FilesList.GetFileString();
                stock.JianCe_Files = item.JianCe_FilesList.GetFileString();
                stock.Attr_Files = item.Attr_FilesList.GetFileString();
                stock.DepartmentID = item.DepartmentID;
                stock.HoisterID = item.HoisterID;
                stock.HoisterName = item.HoisterName;
                stock.HoisterUsageID = item.HoisterUsageID;
                stock.HoisterUsageName = item.HoisterUsageName;
                stock.WireropeTypeID = item.WireropeTypeID;
                stock.WireropeTypeName = item.WireropeTypeName;
                stock.Remark = item.Remark;
                stock.IsOut = false;
                if (stock.KeepDay.HasValue)
                {
                    stock.NextKeepDate = DateTime.Now.AddDays(stock.KeepDay.Value);
                }

                list.Add(stock);
            }

            //_stockRepository.BatchInsert(list);

            _repository.ConfirmForIn(_mapping.Model2Entity(model), _billDetailMapping.Model2Entity(model.BillDetailModels), list);

            return true;
        }
        #endregion

        #region 出库确认  ConfirmForOut
        public bool ConfirmForOut(BillModel model)
        {
            var info = GetByID(model.BillID);

            if (info == null)
            {
                throw new CustomException("当前单子不存在: " + model.BillID);
            }

            if (info.Status != (int)Bill_Status.确认中)
            {
                throw new CustomException("当前单子状态不存在: " + model.BillID);
            }

            model.ConfirmUserID = _currentUser.CurrentUserInfo.UserID;
            model.ConfirmUserName = _currentUser.CurrentUserInfo.UserName;
            model.ConfirmDate = DateTime.Now;
            model.Status = (int)Bill_Status.已确认;

            var where = Expressionable.Create<BillDetail>();
            where = where.And(x => x.BillID == model.BillID);
            var detailList = _billDetailRepository.GetSearch(where).ToList();

            var codeList = detailList.Select(x => x.Code).ToList();

            var where2 = Expressionable.Create<Stock>();
            where2 = where2.And(x => codeList.Contains(x.Code));
            var stockList = _stockRepository.GetSearch(where2).ToList();

            foreach (var item in stockList)
            {
                item.IsOut = true;
            }

            //_stockRepository.BatchUpdate(stockList);
            //Update(info);

            _repository.ConfirmForOut(_mapping.Model2Entity(model), _billDetailMapping.Model2Entity(model.BillDetailModels), stockList);

            return true;
        }
        #endregion
    }
}
